package com.chinatechstar.component.commons.service;

import com.chinatechstar.component.commons.entity.MPage;
import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.component.commons.utils.UuidUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Optional;

public interface BaseService {

    /**
     * 用于获取并解析分页参数
     *
     * @param pageData
     * @return
     */
    default MPage getPageInfo(PageData pageData) {
        MPage page = new MPage();
        String currentPageStr = (String) pageData.get("currentPage");
        String pageSizeStr = (String) pageData.get("pageSize");
        String sorter = (String) pageData.get("sorter");

        currentPageStr = Optional.ofNullable(currentPageStr)
                .orElse("1");
        pageSizeStr = Optional.ofNullable(pageSizeStr)
                .orElse("10");

        int currentPage = Integer.parseInt(currentPageStr);
        int pageSize = Integer.parseInt(pageSizeStr);

        page.setPageSize(pageSize);
        page.setCurrentPage(currentPage);
        page.setSorter(sorter);

        return page;
    }

    /**
     * 初始化排序参数
     *
     * @param param
     * @param sorter
     */
    default void initOrderByParams(Map<String, Object> param, String sorter) {
        if (StringUtils.isNotBlank(sorter)) {
            String sort = sorter.substring(0, sorter.lastIndexOf('_'));
            String sequence =
                    "ascend".equals(sorter.substring(sorter.lastIndexOf('_') + 1)) ? "ASC" : "DESC";
            param.put("sort", sort);
            param.put("sequence", sequence);
        } else {
            param.put("sort", "createTime");
            param.put("sequence", "DESC");
        }
    }

    /**
     * 生成uuid
     *
     * @return
     */
    default String get32UUID() {
        return UuidUtil.get32UUID();
    }
}
